from abc import ABC, abstractmethod
import time

class BaseLLM(ABC):
    def __init__(self, provider_name):
        self.provider_name = provider_name
        self.last_check = None
        self.connection_status = False

    @abstractmethod
    def converse_stream(self, history):
        pass

    def check_connection(self):
        try:
            start_time = time.time()
            result = self._perform_connection_check()
            latency = round((time.time() - start_time)*1000, 2)
            
            self.connection_status = result["status"]
            self.last_check = time.strftime("%Y-%m-%d %H:%M:%S")
            return {
                "provider": self.provider_name,
                "status": "connected" if result["status"] else "disconnected",
                "latency_ms": latency,
                "detail": result.get("detail", "")
            }
        except Exception as e:
            return {
                "provider": self.provider_name,
                "status": "error",
                "detail": f"检查连接时发生异常: {str(e)}"
            }

    @abstractmethod
    def _perform_connection_check(self):
        pass